package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderDetailService;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 处理超时未支付订单
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void processTimeoutOrder(){
        log.info("处理超时未付款的订单：{}",LocalDateTime.now());
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if(list!=null && list.size()>0){
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
            }
        }
        orderService.updateBatchById(list);
    }
    /**
     * 处理一直在配送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨一点触发一次
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void processDeliveryOrder(){
        log.info("处理处于派送中的订单：{}",LocalDateTime.now());
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(1));
        if(list!=null && list.size()>0){
            for (Orders order : list) {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
            }
        }
        orderService.updateBatchById(list);
    }
}
